import React, {Component,} from 'react'
import Admin from "../../../layout/Admin";
import ArticleModel from "../../../model/article";
import {LeftOutlined, RightOutlined, UploadOutlined,} from '@ant-design/icons';
import {
    PageHeader,
    Form, Input, Button, Upload, Modal, Table, Popconfirm, Spin,
} from "antd";
import Info from "../../../service/info";
import {imgPrefix} from "../../../constant/constant";

class Article extends Component {

    constructor(props) {
        super(props)
        this.model = new ArticleModel()
        this.state = {
            list: [],
            article: {
                Title: '',
                Author: '',
                Category: '',
                Id: 0,
                Photo: [],
                Source: '',
                Text: [],
            },
            p: 0,
            offset: 0,
            limit: 15,
            form: {
                title: '',
                source: '',
                author: '',
                category: '',
                text: [],
            },
            imgs: [],
            imgToUpdate: null,
            imgUpdate: [],
            pag: '',
            pagUpdate: '',
            pagUpdateIndex: -1,
            imgUpdateIndex: -1,
            modal: {
                pag: false,
                pagUpdate: false,
                imgUpdate: false,
                add: false,
                detail: false,
            },
            addLoading: false,
            updateLoading: false,
        }
    }

    componentDidMount() {
        this.get()
    }

    get = () => {
        this.model
            .get({
                offset: this.state.offset,
                limit: this.state.limit,
            })
            .then((resp) => {
                const msg = resp.data.message
                if (msg === 'ok') {
                    const list = resp.data.data
                    this.setState({
                        list,
                    })
                }
            })
    }

    add = (params) => {
        this.setState({
            addLoading: true,
        })
        this.model
            .add(params)
            .then((resp) => {
                this.setState({
                    addLoading: false,
                })
                if (resp.data.message === 'ok') {
                    Info.success('文章添加成功')
                    this.form.resetFields()
                    this.modalControl('add', false,)
                }
            })
            .then(() => {
                this.setState({
                    offset: 0,
                    form: {
                        ...this.state.form,
                        text: [],
                    },
                    imgs: [],
                    pag: '',
                }, () => this.get())
            })
    }

    delete = (item) => {
        // id  []int
        // isall int
        const params = {
            isall: 0,
            id: [item.Id,],
        }
        this.model
            .delete(params)
            .then(res => {
                if (res.data.message === 'ok') {
                    Info.success('删除成功')
                } else {
                    Info.error('删除失败')
                }
            })
            .then(() => {
                this.setState({
                    offset: 0,
                }, () => {
                    this.get()
                })
            })
    }

    modalControl = (key, value) => {
        this.setState({
            modal: {
                ...this.state.modal,
                [key]: value,
            }

        })
    }

    nextPage = () => {
        this.setState((state) => ({
            p: state.p + 1,
            offset: state.offset + state.limit,
        }), () => this.get())
    }

    prevPage = () => {
        this.setState((state) => ({
            p: state.p - 1,
            offset: state.offset - state.limit,
        }), () => this.get())
    }

    onAddFinish = (value) => {
        const params = {...value}
        const text = this.state.form.text
        const imgs = this.state.imgs

        let photo = []
        let textStr = ''
        text.map(item => {
            const type = item.type
            if (type === 'img') {
                textStr += `{{${item.name}}}`
                photo.push(item.name)
            } else if (type === 'pag') {
                textStr += item.content
            }
        })
        params.text = textStr
        params.photo = JSON.stringify(photo)
        imgs.map(file => {
            params[file.name] = file
        })
        this.add(params)
    }

    getBase64 = (file) => {
        return new Promise((resolve, reject) => {
            const reader = new FileReader()
            reader.readAsDataURL(file)
            reader.onload = () => resolve(reader.result)
            reader.onerror = error => reject(error)
        })
    }

    callAddPag = () => {
        this.setState({
            modal: {
                ...this.state.modal,
                pag: true,
            }
        })
    }

    checkArticle = (article) => {
        this.modalControl('detail', true,)
        this.setState({
            article: {
                ...article,
                Text: this.parseText(article.Text)
            },
        })
    }

    addPag = () => {
        const pag = this.state.pag
        const text = this.state.form.text
        const newPag = {
            type: 'pag',
            content: pag,
        }
        this.setState({
            form: {
                ...this.state.form,
                text: [...text, newPag,]
            }
        })
    }

    updatePag = () => {
        const pag = this.state.pagUpdate
        const index = this.state.pagUpdateIndex
        const text = [...this.state.article.Text]
        text[index] = {
            type: 'pag',
            content: pag,
        }

        this.setState({
            article: {
                ...this.state.article,
                Text: text,
            }
        }, () => {this.modalControl('pagUpdate', false)})
    }

    deleteTextItem = (index, item) => {
        const text = [...this.state.form.text]
        text.splice(index, 1)
        this.setState({
            form: {
                ...this.state.form,
                text: text,
            }
        })
        if (item.type === 'img') {
            const imgs = [...this.state.imgs]
            const i = imgs.findIndex(img => img.name === item.name)
            imgs.splice(i, 1)
            this.setState({
                imgs: imgs,
            })
        }
    }

    deleteTextItemUpdate = (index, item) => {
        const type = item.type
        const art = this.state.article
        const textArr = [...art.Text]
        // const textArr = this.parseText(textString)
        textArr.splice(index, 1)
        // const newText = this.stringifyTextArr(textArr)
        if (type === 'img') {
            const photo = [...art.Photo]
            const imgIndex = photo.findIndex(src => item.src.endsWith(src))
            photo[imgIndex] = 'delete'
            this.setState({
                article: {
                    ...this.state.article,
                    Photo: photo,
                    Text: textArr,
                }
            })
        } else if (type === 'pag') {
            this.setState({
                article: {
                    ...this.state.article,
                    Text: textArr,
                }
            })
        }
    }

    textItemUpdate = (index, item) => {
        if (item.type === 'pag') {
            this.setState({
                pagUpdate: item.content,
                pagUpdateIndex: index,
            }, () => {
                this.modalControl('pagUpdate', true)
            })
        } else if (item.type === 'img') {
            this.setState({
                imgToUpdate: item,
                imgUpdateIndex: index,
            }, () => {
                this.modalControl('imgUpdate', true)
            })
        }
    }

    stringifyTextArr = arr => {
        let textStr = ''
        arr.map(item => {
            const type = item.type
            if (type === 'img') {
                if (item.update) {
                    textStr += `{{${item.name}}}`
                } else if (item.name) {
                    textStr += `{{${item.name}}}`
                } else {
                    textStr += `{{${item.shortSrc}}}`
                }
            } else if (type === 'pag') {
                textStr += item.content
            }
        })
        return textStr
    }

    parseText = (text) => {
        const arr = []
        let n = 0
        let temp = text
        while (n < text.length) {
            let char = text[n]
            if (char === '{') {
                let end = temp.indexOf('}') + 2
                temp = temp.slice(end)
                let imgStr = text.slice(n + 2, n + end - 2)
                let src = imgStr.startsWith(imgPrefix) ? imgStr : imgPrefix + imgStr
                if (imgStr.startsWith('data:image')) {
                    src = imgStr
                }
                let item = {
                    type: 'img',
                    shortSrc: imgStr,
                    src: src,
                }
                arr.push(item)
                n += end
            } else {
                let end = temp.indexOf('{')
                if (end > -1) {
                    temp = temp.slice(end)
                    let pagStr = text.slice(n, n + end)
                    arr.push({
                        type: 'pag',
                        content: pagStr,
                    })
                    n += end
                } else {
                    let pagStr = temp
                    arr.push({
                        type: 'pag',
                        content: pagStr,
                    })
                    n += temp.length
                }

            }
        }
        return arr
    }

    renderTextItem = item => {
        let template
        let type = item.type
        if (type === 'img') {
            template =  <img
                src={item.src}
                style={{
                    width: '200px',
                    display: 'block'
                }}
                alt={item.name}
            />
        } else if (type === 'pag') {
            template =  <p
                style={{
                    wordBreak: 'break-all',
                }}
            >
                {item.content}
            </p>
        }
        return template
    }

    renderText = (text) => {

        // const arr = this.parseText(text)

        return <div>
            {text.map((item, index) => {
                const content = this.renderTextItem(item)
                const deleteBtn = <Button
                    // onClick={() => this.deleteTextItem(index, item)}
                    onClick={() => this.deleteTextItemUpdate(index, item)}
                >删除</Button>
                const updateBtn = <Button
                    onClick={() => this.textItemUpdate(index, item)}
                >
                    编辑
                </Button>

                return <div
                    key={index}
                    style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center',}}
                >
                    {content}
                    <div>
                        {deleteBtn}
                        {updateBtn}
                    </div>
                </div>
            })}
        </div>
    }

    updateArticle = () => {
        const art = this.state.article
        const params = {
            id: art.Id,
            text: this.stringifyTextArr(art.Text),
            source: art.Source,
            author: art.Author,
            category: art.Category,
            title: art.Title,
            photo: art.Photo === null ? JSON.stringify([]) : JSON.stringify(art.Photo)
        }

        const imgUpdate = this.state.imgUpdate

        for (let [k, v] of Object.entries(imgUpdate)) {
            params[v.name] = v
        }


        this.setState({
            updateLoading: true,
        })
        this.model
            .update(params)
            .then((res) => {
                this.setState({
                    updateLoading: false,
                })

                if (res.data.ok === 1) {
                    Info.success('修改成功')
                    this.setState({
                        article: {
                            Title: '',
                            Author: '',
                            Category: '',
                            Id: 0,
                            Photo: [],
                            Source: '',
                            Text: [],
                        },
                        imgUpdate: [],
                    })
                    this.modalControl('detail', false,)
                }
            })
            .then(() => {
                this.setState({
                    offset: 0,
                }, () => {
                    this.get()
                })
            })
    }

    render() {

        const header = <div style={{background: '#fff'}}>
            <PageHeader title='文章'/>
        </div>

        const layout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 16 },
        }

        const uploadProps = {

            onRemove: file => {
                this.setState(state => {
                    const index = state.imgs.indexOf(file)
                    const indexText = state.form.text.findIndex(t => t.name === file.name)
                    const newFileList = state.imgs.slice()
                    const newTextList = state.form.text.slice()
                    newFileList.splice(index, 1)
                    newTextList.splice(indexText, 1)
                    return {
                        form: {
                            ...state.form,
                            text: newTextList,
                        },
                        imgs: newFileList,
                    }
                })
            },

            beforeUpload: file => {

                this.getBase64(file)
                    .then((base64) => {
                        const text = this.state.form.text
                        this.setState({
                            form: {
                                ...this.state.form,
                                text: [
                                    ...text,
                                    {
                                        type: 'img',
                                        name: file.name,
                                        src: base64,
                                    },
                                ],
                            }
                        })
                    })

                this.setState(state => ({
                    imgs: [...state.imgs, file],
                }))

                return false
            },

        }

        const textContent = <div>
            {this.state.form.text.map(((item, index) => {
                let template = this.renderTextItem(item)

                const edit = <Button
                    onClick={() => this.deleteTextItem(index, item)}
                >删除</Button>
                return <div
                    key={index}
                    style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center',}}
                >
                    {template}
                    {edit}
                </div>
            }))}
        </div>

        const form = <Form
            {...layout}
            ref={el => this.form = el}
            initialValues={this.state.form}
            onFinish={this.onAddFinish}
        >
            <Form.Item
                label="标题"
                name="title"
            >
                <Input />
            </Form.Item>
            <Form.Item
                label="来源"
                name="source"
            >
                <Input />
            </Form.Item>
            <Form.Item
                label="作者"
                name="author"
            >
                <Input />
            </Form.Item>
            <Form.Item
                label="分类"
                name="category"
            >
                <Input />
            </Form.Item>
            <Form.Item
                label="内容"
            >
                {textContent}
                <Button
                    onClick={this.callAddPag}
                >
                    添加段落
                </Button>
                <Upload
                    multiple={false}
                    fileList={this.state.imgs}
                    {...uploadProps}
                >
                    <Button>
                        <UploadOutlined  />
                        插入图片
                    </Button>
                </Upload>
            </Form.Item>

            <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 6 }}>

                <Button
                    onClick={() => this.modalControl('add', false)}
                    style={{marginRight: '8px',}}
                >
                    取消
                </Button>

                <Button
                    type="primary"
                    htmlType="submit"
                >
                    添加
                </Button>

            </Form.Item>

        </Form>


        const modalState = this.state.modal

        const pagModal = <Modal
            title='添加文章段落'
            visible={modalState.pag}
            footer={
                <div>
                    <Button
                        onClick={this.addPag}
                    >确定</Button>
                    <Button
                        onClick={() => this.modalControl('pag', false,)}
                    >取消</Button>
                </div>
            }
            maskClosable={true}
            onCancel={() => this.modalControl('pag', false,)}
        >
            <Input.TextArea
                value={this.state.pag}
                onChange={e => this.setState({pag: e.target.value,})}
            />
        </Modal>

        const pagUpdateModal = <Modal
            title='编辑文章段落'
            visible={modalState.pagUpdate}
            footer={
                <div>
                    <Button
                        onClick={this.updatePag}
                    >确定</Button>
                    <Button
                        onClick={() => this.modalControl('pagUpdate', false,)}
                    >取消</Button>
                </div>
            }
            maskClosable={true}
            onCancel={() => this.modalControl('pagUpdate', false,)}
        >
            <Input.TextArea
                value={this.state.pagUpdate}
                onChange={e => this.setState({pagUpdate: e.target.value,})}
            />
        </Modal>

        const updateUploadProps = {
            onRemove: file => {
                this.setState(state => {
                    const index = state.imgUpdate.indexOf(file)
                    const newFileList = state.imgUpdate.slice()
                    newFileList.splice(index, 1)
                    return {
                        imgUpdate: newFileList,
                    }
                })
            },

            beforeUpload: file => {

                this.getBase64(file)
                    .then((base64) => {
                        // const text = this.state.article.Text
                        const text = [...this.state.article.Text]
                        const index = this.state.imgUpdateIndex
                        text[index] = {
                            name: file.name,
                            src: base64,
                            type: 'img',
                            update: true,
                        }
                        const photo = this.state.article.Photo
                        const imgToUpdateIndex = photo.findIndex(img => imgToUpdate.src.endsWith(img))
                        photo[imgToUpdateIndex] = file.name

                        console.log(imgToUpdate)
                        console.log(photo)

                        this.setState({
                            article: {
                                ...this.state.article,
                                Text: text,
                                Photo: photo
                            }
                        })
                    })

                this.setState(state => ({
                    imgUpdate: [...this.state.imgUpdate, file],
                }))

                return false
            },
        }

        const imgToUpdate = this.state.imgToUpdate
        const imgUpdateModal = <Modal
            title='更换图片'
            visible={modalState.imgUpdate}
            footer={
                <div>
                    <Button
                        // onClick={this.updatePag}
                    >确定</Button>
                    <Button
                        onClick={() => this.modalControl('imgUpdate', false,)}
                    >取消</Button>
                </div>
            }
            maskClosable={true}
            onCancel={() => this.modalControl('imgUpdate', false,)}
        >

            <Upload
                multiple={false}
                fileList={this.state.imgUpdate}
                {...updateUploadProps}
            >
                {imgToUpdate && <img alt={imgToUpdate.name} src={imgToUpdate.src} style={{width: 200,}}/>}

                <Button>
                    <UploadOutlined  />
                    更换图片
                </Button>
            </Upload>

        </Modal>

        const addFormModal = <Modal
            visible={modalState.add}
            width={1000}
            footer={null}
            title='添加文章'
            maskClosable={true}
            onCancel={() => this.modalControl('add', false)}
        >
            <Spin
                spinning={this.state.addLoading}
            >
                {form}
            </Spin>
        </Modal>


        const art = this.state.article
        const {
            Author,
            Category,
            Id,
            Photo,
            Source,
            Text,
            Title,
        } = art
        const detailModal = <Modal
            visible={modalState.detail}
            footer={null}
            title='文章详情'
            maskClosable={true}
            onCancel={() => this.modalControl('detail', false)}
            width={1000}
        >

            <Spin spinning={this.state.updateLoading}>
                <Form
                    {...layout}
                    ref={el => this.detailForm = el}
                    initialValues={this.state.article}
                    onValuesChange={(values, allValues) => {
                        this.setState({
                            article: {
                                ...this.state.article,
                                ...values,
                            }
                        })
                    }}
                >
                    <Form.Item
                        label="Id"
                        // name="Id"
                    >
                        {Id}
                    </Form.Item>
                    <Form.Item
                        label="标题"
                        name="Title"
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="分类"
                        name="Category"
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="作者"
                        name="Author"
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="详情"
                        // name='Text'
                    >
                        {this.renderText(Text)}
                    </Form.Item>
                    <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 6 }}>

                        <Button
                            onClick={() => this.modalControl('detail', false,)}
                            style={{marginRight: '8px',}}
                        >
                            取消
                        </Button>

                        <Button
                            type="primary"
                            onClick={this.updateArticle}
                        >
                            修改
                        </Button>

                    </Form.Item>
                </Form>
            </Spin>

        </Modal>

        // Author: "作者"
        // Category: "分类"
        // Id: 21
        // Photo: ["article/20200701143937.4.jpg"]
        // Source: "来源"
        // Text: "text1{{article/20200701143937.4.jpg}}"
        // Title: "标题"
        const columns = [
            {
                title: 'Id',
                dataIndex: 'Id',
                render: text => <span>{text}</span>,
            },
            {
                title: '分类',
                dataIndex: 'Category',
                render: text => <span>{text}</span>,
            },
            {
                title: '作者',
                dataIndex: 'Author',
                render: text => <span>{text}</span>,
            },
            {
                title: '来源',
                dataIndex: 'Source',
                render: text => <span>{text}</span>,
            },
            {
                title: '标题',
                dataIndex: 'Title',
                render: text => <span>{text}</span>,
            },
            {
                title: '操作',
                render: (text, record) => {
                    return <div>
                        <a
                            style={{marginRight: 8,}}
                            onClick={() => this.checkArticle(record)}
                        >
                            查看文章
                        </a>
                        <a>
                            <Popconfirm
                                title="确定删除?"
                                onConfirm={(e) => this.delete(record)}
                            >
                                <span>删除</span>
                            </Popconfirm >
                        </a>
                    </div>
                }
            }
        ]

        const table = <div className='list-container'>
            <div style={{marginBottom: '16px',}}>
                <Button
                    onClick={() => this.modalControl('add', true)}
                >
                    添加文章
                </Button>
            </div>

            <Table
                dataSource={this.state.list}
                columns={columns}
                rowKey={(record, index) => index}
                pagination={false}
            />

            <div style={{
                paddingTop: 8,
                display: "flex",
                justifyContent: "flex-end",
            }}>
                <Button
                    style={{marginRight: 8,}}
                    onClick={(e) => this.prevPage()}
                ><LeftOutlined /></Button>
                <a className='ant-pagination-item ant-pagination-item-active '>{this.state.p + 1}</a>
                <Button
                    onClick={(e) => this.nextPage()}
                ><RightOutlined /></Button>
            </div>
        </div>

        return <>
            {modalState.pag ? pagModal : null}
            {modalState.pagUpdate ? pagUpdateModal : null}
            {modalState.imgUpdate ? imgUpdateModal : null}
            {modalState.add ? addFormModal : null}
            {modalState.detail ? detailModal : null}
            <Admin>
                {header}
                {table}
            </Admin>
        </>

    }

}
export default Article
